/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2018年09月15日
*   描    述：
*   
================================================================*/


#include <iostream>

using namespace std;


/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: The node where the cycle begins. if there is no cycle, return null
     */
    ListNode * detectCycle(ListNode * head) {
        // write your code here
                // write your code here
        if(head == NULL || head->next == NULL || head->next->next == NULL)
            return NULL;

        ListNode *walker = head;
        ListNode *runner = head;

        while( runner->next != NULL && runner->next->next != NULL ) {
            walker = walker->next;
            runner = runner->next->next;
            if( walker == runner )
                break;
        }

        if( walker == runner ){
            walker = head;
            while( walker != runner ){
                runner = runner->next;
                walker = walker->next;
            }

            return walker;
        }

        return NULL;
    }
};